import dayjs from 'dayjs';
import { Dialog } from 'antd-mobile';

// 提醒项接口
export interface ReminderItem {
  id: string;
  days: number[];
  hour24: number;
  minute: number;
  period: 'AM' | 'PM';
  isActive: boolean;
  createdAt: string;
}

class ReminderService {
  private intervalRef: NodeJS.Timeout | null = null;
  private reminders: ReminderItem[] = [];
  private STORAGE_KEY = 'training_reminders';
  private isInitialized = false;
  private alertedReminders: Set<string> = new Set(); // 防止重复提醒

  // 初始化服务
  init() {
    if (this.isInitialized) return;
    
    this.loadRemindersFromStorage();
    this.startReminderCheck();
    this.isInitialized = true;
    
    console.log('全局提醒服务已初始化');
  }

  // 停止服务
  destroy() {
    if (this.intervalRef) {
      clearInterval(this.intervalRef);
      this.intervalRef = null;
    }
    this.isInitialized = false;
    console.log('全局提醒服务已停止');
  }

  // 从本地存储加载提醒数据
  private loadRemindersFromStorage() {
    try {
      const stored = localStorage.getItem(this.STORAGE_KEY);
      if (stored) {
        this.reminders = JSON.parse(stored);
        console.log('从本地存储加载提醒数据:', this.reminders);
      }
    } catch (error) {
      console.error('加载提醒数据失败:', error);
    }
  }

  // 保存提醒数据到本地存储
  private saveRemindersToStorage() {
    try {
      localStorage.setItem(this.STORAGE_KEY, JSON.stringify(this.reminders));
      console.log('提醒数据已保存到本地存储:', this.reminders);
    } catch (error) {
      console.error('保存提醒数据失败:', error);
    }
  }

  // 添加提醒
  addReminder(reminder: ReminderItem) {
    this.reminders.push(reminder);
    this.saveRemindersToStorage();
    console.log('添加提醒:', reminder);
    
    // 立即检查一次，以防错过提醒
    this.checkReminders();
    
    // 重新启动定时器
    this.restartReminderCheck();
  }

  // 删除提醒
  removeReminder(id: string) {
    this.reminders = this.reminders.filter(r => r.id !== id);
    this.saveRemindersToStorage();
    console.log('删除提醒:', id);
  }

  // 更新提醒
  updateReminder(id: string, updates: Partial<ReminderItem>) {
    this.reminders = this.reminders.map(r => 
      r.id === id ? { ...r, ...updates } : r
    );
    this.saveRemindersToStorage();
    console.log('更新提醒:', id, updates);
  }

  // 获取所有提醒
  getReminders(): ReminderItem[] {
    return [...this.reminders];
  }

  // 检查提醒时间是否到达
  private checkReminders() {
    const now = dayjs();
    const currentDay = now.day(); // 获取当前星期几 (0-6)
    const currentHour = now.hour();
    const currentMinute = now.minute();

    // 每天清理一次过期的提醒记录
    this.cleanupAlertedReminders();

    console.log('全局检查提醒时间:', {
      currentTime: now.format('YYYY-MM-DD HH:mm:ss'),
      currentDay,
      currentHour,
      currentMinute,
      remindersCount: this.reminders.length,
      activeReminders: this.reminders.filter(r => r.isActive).length
    });

    this.reminders.forEach(reminder => {
      if (!reminder.isActive) return;
      
      // 检查今天是否在提醒的日期列表中
      if (!reminder.days.includes(currentDay)) return;
      
      // 计算时间差（以秒为单位）
      const currentTimeInSeconds = currentHour * 3600 + currentMinute * 60 + now.second();
      const reminderTimeInSeconds = reminder.hour24 * 3600 + reminder.minute * 60;
      const timeDiffInSeconds = Math.abs(currentTimeInSeconds - reminderTimeInSeconds);
      
      // 检查是否在3秒范围内
      const isWithin3Seconds = timeDiffInSeconds <= 3;
      const reminderKey = `${reminder.id}_${currentDay}_${reminder.hour24}_${reminder.minute}`;
      
      console.log('检查提醒:', {
        reminderId: reminder.id,
        reminderTime: `${reminder.hour24}:${reminder.minute}`,
        currentTime: `${currentHour}:${currentMinute}:${now.second()}`,
        timeDiffInSeconds,
        isWithin3Seconds,
        alreadyAlerted: this.alertedReminders.has(reminderKey)
      });
      
      if (isWithin3Seconds && !this.alertedReminders.has(reminderKey)) {
        // 标记为已提醒，防止重复
        this.alertedReminders.add(reminderKey);
        
        // 显示全局提醒弹窗
        this.showGlobalReminderDialog(reminder);
      }
    });
  }

  // 显示全局提醒弹窗
  private showGlobalReminderDialog(reminder: ReminderItem) {
    const hour12 = reminder.hour24 % 12 === 0 ? 12 : reminder.hour24 % 12;
    const formattedTime = `${hour12.toString().padStart(2, '0')}:${reminder.minute.toString().padStart(2, '0')} ${reminder.period}`;
    
    console.log('显示全局提醒弹窗:', {
      reminder,
      formattedTime,
      currentTime: dayjs().format('YYYY-MM-DD HH:mm:ss')
    });
    
    // 使用全局弹窗，确保在任何页面都能显示
    Dialog.alert({
      title: '🏃‍♂️ 训练提醒',
      content: `设置的训练时间 ${formattedTime} 到了！\n\n准备开始训练吧！`,
      confirmText: '开始训练',
      onConfirm: () => {
        console.log('用户确认了全局提醒，准备开始训练');
        // 可以在这里添加跳转到训练页面的逻辑
        // 或者播放提示音等
      }
    });
  }

  // 启动提醒检查定时器
  private startReminderCheck() {
    if (this.reminders.length > 0 && this.reminders.some(r => r.isActive)) {
      // 先清除现有定时器
      if (this.intervalRef) {
        clearInterval(this.intervalRef);
      }
      
      // 设置更频繁的检查间隔（每3秒检查一次）
      this.intervalRef = setInterval(() => {
        this.checkReminders();
      }, 3000); // 每3秒检查一次
      console.log('全局提醒检查定时器已启动，每3秒检查一次');
    } else {
      console.log('没有活跃的提醒，停止定时器');
    }
  }

  // 重新启动提醒检查（当提醒列表更新时调用）
  restartReminderCheck() {
    if (this.intervalRef) {
      clearInterval(this.intervalRef);
    }
    this.startReminderCheck();
  }

  // 清理过期的提醒记录（每天清理一次）
  private cleanupAlertedReminders() {
    const now = dayjs();
    const today = now.format('YYYY-MM-DD');
    
    // 清理昨天的提醒记录
    this.alertedReminders.forEach(key => {
      if (!key.includes(today)) {
        this.alertedReminders.delete(key);
      }
    });
  }

  // 添加调试方法
  getDebugInfo() {
    return {
      isInitialized: this.isInitialized,
      remindersCount: this.reminders.length,
      activeReminders: this.reminders.filter(r => r.isActive).length,
      hasInterval: !!this.intervalRef,
      alertedCount: this.alertedReminders.size,
      currentTime: dayjs().format('YYYY-MM-DD HH:mm:ss')
    };
  }
}

// 创建全局单例实例
export const reminderService = new ReminderService();
